package com.yangquan.visibility;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 通过 ReentrantLock 保证变量的可见性
// 锁的获取和释放会触发主内存与线程缓存的同步
public class LockFix {
    private static boolean flag = false;
    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                lock.lock();
                try {
                    if (flag) break;
                } finally { lock.unlock(); }
            }
            System.out.println("线程 1 退出循环");
        }).start();

        new Thread(() -> {
            try { Thread.sleep(1000); } 
            catch (InterruptedException e) {}
            lock.lock();
            try { flag = true; } 
            finally { lock.unlock(); }
            System.out.println("线程 2 修改 flag 为 true");
        }).start();
    }
}

